package ua.khuta.myskidka;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ua.khuta.facebook.Facebook;
import ua.khuta.vk.Vk;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Session;

public class FragmentLogin extends FragmentActivity implements OnClickListener {
	Button btnEnter, btnRegistration;
	EditText etLoginEmail, etLoginPassword;
	ImageView btnStartFacebook, btnStartVk;
	ProgressDialog progDailog = null;
	Fragment fragNews;
	TextView tvFace;
	private final int REQUEST_LOGIN = 1;
	// url to make request
	private static String url = "http://cl223044.tmweb.ru/auth/json?email=";
	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_USERID = "userID";
	private static final String TAG_ERROR = "error";
	String result = "";// result of registration
	String error = "";// error with registration
	int userID;
	// news JSONArray
	JSONArray loginResult = null;
	Database db;
	Intent intent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_login);
		try {
			PackageInfo info = getPackageManager().getPackageInfo(
					"ua.khuta.myskidka", PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				Log.d("myLogs",
						Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (NameNotFoundException e) {

		} catch (NoSuchAlgorithmException e) {

		}
		initialization();
		db = Database.getInstance(this);

	}



	public void initialization() {
		etLoginEmail = (EditText) findViewById(R.id.et_login_email);
		etLoginPassword = (EditText) findViewById(R.id.et_login_password);
		btnEnter = (Button) findViewById(R.id.btn_login);
		btnRegistration = (Button) findViewById(R.id.btn_start_registration);
		btnEnter.setOnClickListener(this);
		btnRegistration.setOnClickListener(this);

		btnStartFacebook = (ImageButton) findViewById(R.id.btn_start_facebook);
		btnStartFacebook.setOnClickListener(this);
		btnStartVk = (ImageButton) findViewById(R.id.btn_start_vk);
		btnStartVk.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			String login = etLoginEmail.getText().toString();
			String password = etLoginPassword.getText().toString();
			// Make url!!
			GetJSON getJSON = new GetJSON();
			getJSON.execute();
			break;
		case R.id.btn_start_registration:
			Fragment fragReg = new FragmentRegistration();
			FragmentTransaction fragTrans = getSupportFragmentManager()
					.beginTransaction().replace(R.id.content_frame, fragReg);
			fragTrans.commit();
			break;
		case R.id.btn_start_facebook:
			intent = new Intent(FragmentLogin.this, Facebook.class);
			startActivity(intent);
		case R.id.btn_start_vk:
			intent = new Intent(FragmentLogin.this, Vk.class);
			startActivity(intent);
			break;
		default:
			break;
		}

	}

	class GetJSON extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			// Creating JSON Parser instance
			JSONParser jParser = new JSONParser();
			url += etLoginEmail.getText().toString() + "&password="
					+ etLoginPassword.getText().toString();
			Log.d("myLogs", url);
			// getting JSON string from URL
			JSONObject json = jParser.getJSONFromUrl(url);
			Log.d("myLogs", json.toString());

			try {
				Log.d("myLogs", json.getString(TAG_SUCCESS));
				result = json.getString(TAG_SUCCESS);
				if (result.equals("true")) {
					userID = json.getInt(TAG_USERID);
				} else {
					error = json.getString(TAG_ERROR);
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			Log.d("myLogs", "result=" + result);
			if (result.equals("true")) {// ERROR!!!!
				Toast.makeText(FragmentLogin.this, "Registration is SUCCESS",
						2000).show();
				db.addPerson(userID, "", "", "", etLoginEmail.getText()
						.toString(), "", "", "", db.mDB);

				fragNews = new FragmentNews();
				// Fragment fragNews=new FragmentRegistration();
				FragmentTransaction fragTrans = getSupportFragmentManager()
						.beginTransaction().replace(R.id.content_frame,
								fragNews);
				fragTrans.commit();
			} else {

				Toast.makeText(FragmentLogin.this, error, 2000).show();
				url = "http://cl220875.tmweb.ru/auth/json?email=";
			}
			super.onPostExecute(result);

		}

	}
}
